/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.ispc.foundation.io;

import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by Peter on 2016/8/24.
 */
public class ProcessStreamHelper extends Thread {
    public static final String ERROR = "Error";
    public static final String OUTPUT = "Output";

    private InputStream is;
    private String type;
    private List<String> result = Lists.newLinkedList();
    private ProcessCallBack callback;

    public ProcessStreamHelper(InputStream is, String type) {
        this.is = is;
        this.type = type;
        this.callback = null;
    }
    public ProcessStreamHelper(InputStream is, String type, ProcessCallBack callback) {
        this.is = is;
        this.type = type;
        this.callback = callback;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            while ((line = br.readLine()) != null) {
                if (type.equals(ERROR)) {
                    result.add(line);
//                    System.out.println(ERROR + ":" + line);
                } else {
                    //result += line;
                    result.add(line);
                }
            }

            if (callback != null) {
                callback.readAll(result);
            }
            br.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public List<String> getResult() {
        return result;
    }

    public interface ProcessCallBack {
        void readAll(List<String> arg);
    }
}
